package com.travel.ticket.service.impl;

import com.travel.common.to.TicketTo;
import com.travel.ticket.entity.SpuInfoEntity;
import com.travel.ticket.service.SkuInfoService;
import com.travel.ticket.service.SpuInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.travel.common.utils.PageUtils;
import com.travel.common.utils.Query;

import com.travel.ticket.dao.CollectionDao;
import com.travel.ticket.entity.CollectionEntity;
import com.travel.ticket.service.CollectionService;


@Service("collectionService")
public class CollectionServiceImpl extends ServiceImpl<CollectionDao, CollectionEntity> implements CollectionService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    SpuInfoService spuInfoService;

    @Autowired
    SkuInfoService skuInfoService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CollectionEntity> page = this.page(
                new Query<CollectionEntity>().getPage(params),
                new QueryWrapper<CollectionEntity>()
        );

        return new PageUtils(page);
    }



    /**
     * 获取该用户是否对该spu有收藏
     * @param spuId
     * @param userId
     * @return
     */
    @Override
    public Boolean isCollection(Integer spuId, Integer userId) {
        //1. 获取对应spuId的收藏过的 所有userId
        String key = "ticket_collectionInfo:"+spuId;
        List<String> userIdList = redisTemplate.opsForList().range(key, 0, -1);

        //2. 判断 这里取出的id为String 要转为String来判断
        boolean isCollection = userIdList.contains(String.valueOf(userId));

        return isCollection;
    }

    /**
     * 添加收藏记录
     * @param spuId
     * @param userId
     */
    @Override
    public void saveCollection(Integer spuId, Integer userId) {
        //1. 更改redis中的收藏数 key:collectionNum:spuId  value:22
        String key = "ticket_collectionNum:"+spuId;
        String s = redisTemplate.opsForValue().get(key);
        //1.1 有记录 取出+1
        if(s != null && s.length() != 0){
            int collectionNum = Integer.parseInt(s);
            redisTemplate.opsForValue().set(key,String.valueOf(collectionNum+1));
        }else{
            //1.2 没有记录 添加
            redisTemplate.opsForValue().set(key,String.valueOf(1));
        }

        //2. 保存收藏记录到redis key:collectionInfo:spuId:  value:userId
        String k = "ticket_collectionInfo:"+spuId;
        redisTemplate.opsForList().leftPush(k,String.valueOf(userId));

        //3. 保存记录到数据库
        CollectionEntity collectionEntity = new CollectionEntity();
        collectionEntity.setUserId(userId);
        collectionEntity.setSpuId(spuId);
        collectionEntity.setUpdateTime(new Date());
        collectionEntity.setAddTime(new Date());

        this.save(collectionEntity);

        //TODO 后台对点收藏没有实时性要求，不特定去修改数据库中的点赞数
        // 启定时任务，每3分钟同步mysql和redis中的收藏数

    }

    /**
     * 删除收藏记录
     * @param spuId
     * @param userId
     */
    @Override
    public void deleteCollection(Integer spuId, Integer userId) {
        //1. 更改redis中的收藏数
        String key = "ticket_collectionNum:"+spuId;
        String s = redisTemplate.opsForValue().get(key);

        int collectionNum = Integer.parseInt(s);
        redisTemplate.opsForValue().set(key,String.valueOf(collectionNum-1));
        System.out.println(collectionNum-1);

        //2. redis中删除收藏记录
        redisTemplate.opsForList().remove("ticket_collectionInfo:"+spuId,0,String.valueOf(userId));

        //3. mysql中删除收藏记录
        this.baseMapper.delete(new QueryWrapper<CollectionEntity>()
                .eq("spu_id",spuId)
                .eq("user_id",userId));

        // TODO 后台对收藏没有实时性要求，不特定去修改数据库中的点赞数
        // 启定时任务，每3分钟同步mysql和redis中的点赞数
    }

    /**
     * 获取用户收藏的票务信息
     * @param memberId
     * @return
     */
    @Override
    public List<TicketTo> getMyTicketCollection(Long memberId) {
        List<TicketTo> ticketTos = new ArrayList<>();

        List<CollectionEntity> collectionEntities = this.baseMapper.selectList(new QueryWrapper<CollectionEntity>().eq("user_id", memberId));
        // 所有收藏的spuId
        List<Integer> collect = collectionEntities.stream()
                .map(CollectionEntity::getSpuId)
                .collect(Collectors.toList());
        // 获取所有spu信息封装成TicketTo
        for (Integer spuId : collect) {
            SpuInfoEntity byId = spuInfoService.getById(spuId);
            TicketTo ticketTo = new TicketTo();
            // 属性对拷
            BeanUtils.copyProperties(byId,ticketTo);
            // 获取该spu对应所有sku中的最低价格 用于页面展示
            BigDecimal price = spuInfoService.getMinPrice(spuId);
            // 不保留小数点
            ticketTo.setPrice(price.setScale(0, RoundingMode.DOWN));

            ticketTos.add(ticketTo);
        }

        return ticketTos;
    }



}